package view;

import com.toedter.calendar.JDateChooser;
import model.*;
import service.*;
import utils.DatabaseUtil;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.*;
import java.awt.*;
import java.io.File;
import java.lang.Class;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.sql.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import com.toedter.calendar.IDateEvaluator;
import javax.swing.JButton;
import java.awt.Color;

public class GradeInputPanel extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);

    private User currentUser;
    private JComboBox<String> classCombo;
    private JComboBox<String> subjectCombo;
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private Map<String, Integer> classIdMap = new HashMap<>();
    private Map<String, Integer> subjectIdMap = new HashMap<>();
    private JComboBox<String> examTypeCombo;
    private JDateChooser examDateChooser;
    private JButton clearButton;
    private JPopupMenu tablePopupMenu;

    // 添加当前选中的班级和科目ID
    private int selectedClassId = -1;
    private int selectedSubjectId = -1;

    private Set<Date> datesWithGrades = new HashSet<>();

    public GradeInputPanel(User currentUser) {
        this.currentUser = currentUser;
        initComponents();
        loadTeacherClasses();

        // 设置默认日期为今天
        examDateChooser.setDate(new Date());

        // 初始更新日期高亮
        if (selectedSubjectId != -1) {
            updateDatesWithGrades();
        }
    }

    private void initComponents() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部控制面板，使用 GridBagLayout 以获得更好的布局控制
        JPanel controlPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 班级和科目选择面板
        JPanel selectionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        classCombo = new JComboBox<>();
        classCombo.setFont(CONTENT_FONT);
        classCombo.setPreferredSize(new Dimension(150, 25));

        subjectCombo = new JComboBox<>();
        subjectCombo.setFont(CONTENT_FONT);
        subjectCombo.setPreferredSize(new Dimension(150, 25));

        selectionPanel.add(new JLabel("选择班级："));
        selectionPanel.add(classCombo);
        selectionPanel.add(new JLabel("选择课程："));
        selectionPanel.add(subjectCombo);

        // 考试信息面板
        JPanel examPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        examTypeCombo = new JComboBox<>(new String[]{"期中考试", "期末考试", "单元测试", "补考"});
        examTypeCombo.setFont(CONTENT_FONT);
        examTypeCombo.setPreferredSize(new Dimension(120, 25));

        examDateChooser = new JDateChooser();
        examDateChooser.setFont(CONTENT_FONT);
        examDateChooser.setDateFormatString("yyyy-MM-dd");
        examDateChooser.setPreferredSize(new Dimension(120, 25));

        // 自定义日期渲染器
        DefaultDayRenderer renderer = new DefaultDayRenderer();
        examDateChooser.getJCalendar().getDayChooser().addDateEvaluator(renderer);
        examDateChooser.getJCalendar().getDayChooser().setDecorationBackgroundVisible(true);
        examDateChooser.getJCalendar().getDayChooser().setDecorationBordersVisible(true);

        examPanel.add(new JLabel("考试类型："));
        examPanel.add(examTypeCombo);
        examPanel.add(new JLabel("考试日期："));
        examPanel.add(examDateChooser);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JButton saveButton = new JButton("保存成绩");
        JButton importButton = new JButton("导入成绩");
        JButton exportButton = new JButton("导出成绩");
        clearButton = new JButton("清空成绩");

        saveButton.setFont(CONTENT_FONT);
        importButton.setFont(CONTENT_FONT);
        exportButton.setFont(CONTENT_FONT);
        clearButton.setFont(CONTENT_FONT);

        buttonPanel.add(saveButton);
        buttonPanel.add(importButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(clearButton);

        // 添加到控制面板
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        controlPanel.add(selectionPanel, gbc);

        gbc.gridy = 1;
        controlPanel.add(examPanel, gbc);

        gbc.gridy = 2;
        controlPanel.add(buttonPanel, gbc);

        add(controlPanel, BorderLayout.NORTH);

        // 创建成绩表格
        String[] columnNames = {"学号", "姓名", "成绩", "考试类型", "考试日期", "学生ID"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 2; // 只允许编辑成绩列
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                switch (columnIndex) {
                    case 2: return Double.class;  // 成绩列使用Double类型
                    case 4: return Date.class;    // 日期列使用Date类型
                    case 5: return Integer.class;  // 学生ID列使用Integer类型
                    default: return String.class;
                }
            }
        };

        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);
        gradeTable.setRowHeight(25);

        // 隐藏学生ID列
        gradeTable.getColumnModel().getColumn(5).setMinWidth(0);
        gradeTable.getColumnModel().getColumn(5).setMaxWidth(0);
        gradeTable.getColumnModel().getColumn(5).setWidth(0);

        // 设置日期列的渲染器
        gradeTable.getColumnModel().getColumn(4).setCellRenderer(new DefaultTableCellRenderer() {
            private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus,
                                                           int row, int column) {
                if (value instanceof Date) {
                    value = sdf.format((Date) value);
                }
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        });

        // 设置成绩列的编辑器，限制输入范围为0-100
        gradeTable.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(
                new JTextField()) {
            @Override
            public boolean stopCellEditing() {
                try {
                    String value = getCellEditorValue().toString().trim();
                    if (value.isEmpty()) {
                        return super.stopCellEditing();
                    }
                    double score = Double.parseDouble(value);
                    if (score >= 0 && score <= 100) {
                        return super.stopCellEditing();
                    }
                    JOptionPane.showMessageDialog(gradeTable,
                            "请输入0-100之间的分数！", "输入错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(gradeTable,
                            "请输入有效的分数！", "输入错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            }
        });

        add(new JScrollPane(gradeTable), BorderLayout.CENTER);

        // 创建表格右键菜单
        createTablePopupMenu();

        // 添加所有监听器
        addListeners();

        // 添加按钮事件监听器
        saveButton.addActionListener(e -> saveGrades());
        importButton.addActionListener(e -> importGrades());
        exportButton.addActionListener(e -> exportGrades());
        clearButton.addActionListener(e -> clearGrades());
    }

    private void loadTeacherClasses() {
        // 暂时移除 actionListener 以防止触发更新
        ActionListener[] listeners = classCombo.getActionListeners();
        for (ActionListener listener : listeners) {
            classCombo.removeActionListener(listener);
        }

        classCombo.removeAllItems();
        classIdMap.clear();

        String sql = "SELECT DISTINCT c.id, c.class_name " +
                "FROM subject_teachers st " +
                "JOIN classes c ON st.class_id = c.id " +
                "WHERE st.teacher_id = ? " +
                "ORDER BY c.class_name";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, currentUser.getId());
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                String className = rs.getString("class_name");
                int classId = rs.getInt("id");
                classIdMap.put(className, classId);
                classCombo.addItem(className);
            }

            // 如果有班级，选择第一个
            if (classCombo.getItemCount() > 0) {
                classCombo.setSelectedIndex(0);
                selectedClassId = classIdMap.get(classCombo.getSelectedItem());
            }

            // 重新添加 actionListener
            classCombo.addActionListener(e -> updateSubjects());

            // 初始加载科目
            updateSubjects();

        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载班级列表失败：" + e.getMessage());
        }
    }

    private void updateSubjects() {
        String selectedClass = (String) classCombo.getSelectedItem();
        if (selectedClass == null) return;

        Integer classId = classIdMap.get(selectedClass);
        if (classId == null) return;

        // 更新选中的班级ID
        selectedClassId = classId;

        // 暂时移除 actionListener
        ActionListener[] listeners = subjectCombo.getActionListeners();
        for (ActionListener listener : listeners) {
            subjectCombo.removeActionListener(listener);
        }

        // 清空科目下拉框
        subjectCombo.removeAllItems();
        subjectIdMap.clear();

        // 加载该班级的科目
        String sql = "SELECT DISTINCT s.id, s.subject_name " +
                "FROM subjects s " +
                "JOIN subject_teachers st ON s.id = st.subject_id " +
                "WHERE st.teacher_id = ? AND st.class_id = ? " +
                "ORDER BY s.subject_name";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, currentUser.getId());
            stmt.setInt(2, selectedClassId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                String subjectName = rs.getString("subject_name");
                int subjectId = rs.getInt("id");
                subjectCombo.addItem(subjectName);
                subjectIdMap.put(subjectName, subjectId);
            }

            // 如果有科目，选择第一个并更新日期高亮
            if (subjectCombo.getItemCount() > 0) {
                subjectCombo.setSelectedIndex(0);
                selectedSubjectId = subjectIdMap.get(subjectCombo.getSelectedItem());
                updateDatesWithGrades();
                loadGrades();
            }

            // 重新添加 actionListener
            subjectCombo.addActionListener(e -> loadGrades());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void loadGrades() {
        String selectedSubject = (String) subjectCombo.getSelectedItem();
        if (selectedSubject == null) return;

        Integer subjectId = subjectIdMap.get(selectedSubject);
        if (subjectId == null) return;  // 添加空值检查

        // 更新选中的科目ID
        selectedSubjectId = subjectId;

        // 刷新表格数据
        refreshTable();
    }

    private void saveGrades() {
        String className = (String) classCombo.getSelectedItem();
        String subjectName = (String) subjectCombo.getSelectedItem();
        if (className == null || subjectName == null) return;

        Integer classId = classIdMap.get(className);
        Integer subjectId = subjectIdMap.get(subjectName);
        if (classId == null || subjectId == null) return;

        // 获取考试类型和日期
        String examType = (String) examTypeCombo.getSelectedItem();
        java.util.Date examDate = examDateChooser.getDate();
        if (examType == null || examDate == null) {
            JOptionPane.showMessageDialog(this, "请选择考试类型和日期！");
            return;
        }

        // 在需要转换为 SQL Date 的地方使用明确的转换
        java.sql.Date sqlDate = new java.sql.Date(examDate.getTime());

        try (Connection conn = DatabaseUtil.getConnection()) {
            conn.setAutoCommit(false);

            String sql = "INSERT INTO grades (student_id, subject_id, score, exam_type, exam_date) " +
                    "VALUES (?, ?, ?, ?, ?) " +
                    "ON DUPLICATE KEY UPDATE score = ?";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                for (int row = 0; row < tableModel.getRowCount(); row++) {
                    Object scoreObj = tableModel.getValueAt(row, 2);
                    if (scoreObj != null && !scoreObj.toString().trim().isEmpty()) {
                        double score = Double.parseDouble(scoreObj.toString());
                        int studentId = (int) tableModel.getValueAt(row, 5); // 从隐藏列获取学生ID

                        stmt.setInt(1, studentId);
                        stmt.setInt(2, selectedSubjectId);
                        stmt.setDouble(3, score);
                        stmt.setString(4, examType);
                        stmt.setDate(5, sqlDate);
                        stmt.setDouble(6, score);
                        stmt.addBatch();
                    }
                }

                stmt.executeBatch();
                conn.commit();
                JOptionPane.showMessageDialog(this, "成绩保存成功！");
                refreshTable();  // 刷新显示最新数据
                updateDatesWithGrades();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败：" + e.getMessage());
        }
    }

    private void importGrades() {
        // TODO: 实现成绩导入功能
        JOptionPane.showMessageDialog(this, "成绩导入功能待实现");
    }

    private void exportGrades() {
        // TODO: 实现成绩导出功能
        JOptionPane.showMessageDialog(this, "成绩导出功能待实现");
    }

    private void refreshTable() {
        // 获取当前选择的考试类型和日期
        String examType = (String) examTypeCombo.getSelectedItem();
        Date examDate = examDateChooser.getDate();

        // 如果考试类型或日期为空，清空表格并返回
        if (examType == null || examDate == null) {
            tableModel.setRowCount(0);
            return;
        }

        // 清空表格
        tableModel.setRowCount(0);

        // 获取班级学生列表和成绩
        String sql = "SELECT s.id as student_id, u.username as student_no, u.name as student_name, " +
                "g.score, g.exam_type, g.exam_date " +
                "FROM students s " +
                "JOIN users u ON s.user_id = u.id " +
                "JOIN classes c ON s.class_id = c.id " +
                "LEFT JOIN grades g ON s.id = g.student_id " +
                "AND g.subject_id = ? AND g.exam_type = ? AND DATE(g.exam_date) = ? " +
                "WHERE c.id = ? " +
                "ORDER BY u.username";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, selectedSubjectId);
            stmt.setString(2, examType);
            stmt.setDate(3, new java.sql.Date(examDate.getTime()));
            stmt.setInt(4, selectedClassId);

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Object[] rowData = {
                        rs.getString("student_no"),
                        rs.getString("student_name"),
                        rs.getDouble("score"),  // 使用getDouble以确保返回值为Double类型
                        rs.getString("exam_type"),
                        rs.getDate("exam_date"),
                        rs.getInt("student_id")  // 隐藏的学生ID列
                };
                tableModel.addRow(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "获取学生列表失败：" + e.getMessage());
        }
    }

    private Map<Integer, Double> getExistingGrades(int classId, int subjectId, String examType, java.util.Date examDate) {
        Map<Integer, Double> grades = new HashMap<>();
        String sql = "SELECT g.student_id, g.score " +
                "FROM grades g " +
                "JOIN students s ON g.student_id = s.id " +
                "WHERE s.class_id = ? AND g.subject_id = ? " +
                "AND g.exam_type = ? AND DATE(g.exam_date) = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, classId);
            stmt.setInt(2, subjectId);
            stmt.setString(3, examType);
            stmt.setDate(4, new java.sql.Date(examDate.getTime()));

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                grades.put(rs.getInt("student_id"), rs.getDouble("score"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return grades;
    }

    private void createTablePopupMenu() {
        tablePopupMenu = new JPopupMenu();
        JMenuItem deleteMenuItem = new JMenuItem("删除成绩");
        deleteMenuItem.addActionListener(e -> deleteSelectedGrade());
        tablePopupMenu.add(deleteMenuItem);

        // 添加表格右键菜单监听器
        gradeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = gradeTable.rowAtPoint(e.getPoint());
                    if (row >= 0) {
                        gradeTable.setRowSelectionInterval(row, row);
                        // 只有当该行有成绩时才显示右键菜单
                        Object score = gradeTable.getValueAt(row, 2);
                        if (score != null) {
                            tablePopupMenu.show(e.getComponent(), e.getX(), e.getY());
                        }
                    }
                }
            }
        });
    }

    private void addListeners() {
        // 考试类型改变时更新日期高亮和表格
        examTypeCombo.addActionListener(e -> {
            updateDatesWithGrades();
            refreshTable();
        });

        // 日期改变时刷新表格
        examDateChooser.getDateEditor().addPropertyChangeListener(evt -> {
            if ("date".equals(evt.getPropertyName())) {
                Date selectedDate = examDateChooser.getDate();
                if (selectedDate != null) {
                    if (datesWithGrades.contains(removeTime(selectedDate))) {
                        examDateChooser.setBackground(new Color(255, 200, 200));
                    } else {
                        examDateChooser.setBackground(UIManager.getColor("TextField.background"));
                    }
                }
                refreshTable();
            }
        });

        // 科目改变时更新日期高亮和表格
        subjectCombo.addActionListener(e -> {
            String selectedSubject = (String) subjectCombo.getSelectedItem();
            if (selectedSubject != null) {
                selectedSubjectId = subjectIdMap.get(selectedSubject);
                updateDatesWithGrades();
                refreshTable();
            }
        });

        // 添加清空按钮的监听器
        clearButton.addActionListener(e -> clearGrades());
    }

    private void clearGrades() {
        // 确认是否清空成绩
        int result = JOptionPane.showConfirmDialog(
                this,
                "确定要清空当前考试的所有成绩吗？\n此操作不可恢复！",
                "确认清空",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE
        );

        if (result != JOptionPane.YES_OPTION) {
            return;
        }

        String examType = (String) examTypeCombo.getSelectedItem();
        java.util.Date examDate = examDateChooser.getDate();

        if (examType == null || examDate == null) {
            JOptionPane.showMessageDialog(this, "请选择考试类型和日期！");
            return;
        }

        // 删除成绩
        String sql = "DELETE FROM grades WHERE subject_id = ? AND exam_type = ? " +
                "AND DATE(exam_date) = ? AND student_id IN " +
                "(SELECT id FROM students WHERE class_id = ?)";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, selectedSubjectId);
            stmt.setString(2, examType);
            stmt.setDate(3, new java.sql.Date(examDate.getTime()));
            stmt.setInt(4, selectedClassId);

            int count = stmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "已清空 " + count + " 条成绩记录！");

            // 刷新表格
            refreshTable();
            updateDatesWithGrades();
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "清空成绩失败：" + ex.getMessage());
        }
    }

    private void deleteSelectedGrade() {
        int row = gradeTable.getSelectedRow();
        if (row < 0) return;

        // 获取学生信息
        String studentNo = (String) gradeTable.getValueAt(row, 0);
        String studentName = (String) gradeTable.getValueAt(row, 1);
        int studentId = (int) gradeTable.getValueAt(row, 5); // 从隐藏列获取学生ID

        // 确认是否删除
        int result = JOptionPane.showConfirmDialog(
                this,
                "确定要删除学生 " + studentNo + " " + studentName + " 的成绩吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE
        );

        if (result != JOptionPane.YES_OPTION) {
            return;
        }

        String examType = (String) examTypeCombo.getSelectedItem();
        java.util.Date examDate = examDateChooser.getDate();

        // 删除成绩
        String sql = "DELETE FROM grades WHERE student_id = ? AND subject_id = ? " +
                "AND exam_type = ? AND DATE(exam_date) = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, studentId);
            stmt.setInt(2, selectedSubjectId);
            stmt.setString(3, examType);
            stmt.setDate(4, new java.sql.Date(examDate.getTime()));

            if (stmt.executeUpdate() > 0) {
                JOptionPane.showMessageDialog(this, "成绩删除成功！");
                // 清空表格中的成绩
                gradeTable.setValueAt(null, row, 2);
            }
            updateDatesWithGrades();
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "删除成绩失败：" + ex.getMessage());
        }
    }

    // 修改日期渲染器的实现
    private class DefaultDayRenderer implements IDateEvaluator {
        @Override
        public boolean isSpecial(Date date) {
            if (date == null) return false;
            Date normalizedDate = removeTime(date);
            boolean hasGrades = false;
            for (Date gradeDate : datesWithGrades) {
                if (removeTime(gradeDate).equals(normalizedDate)) {
                    hasGrades = true;
                    break;
                }
            }
            return hasGrades;
        }

        @Override
        public String getSpecialTooltip() {
            return "该日期有成绩记录";
        }

        @Override
        public Color getSpecialBackroundColor() {
            return new Color(255, 100, 100); // 使用更鲜艳的红色
        }

        @Override
        public Color getSpecialForegroundColor() {
            return Color.WHITE;  // 使用白色文字，更容易看清
        }

        @Override
        public boolean isInvalid(Date date) {
            return false;
        }

        @Override
        public String getInvalidTooltip() {
            return null;
        }

        @Override
        public Color getInvalidBackroundColor() {
            return null;
        }

        @Override
        public Color getInvalidForegroundColor() {
            return null;
        }
    }

    private void updateDatesWithGrades() {
        datesWithGrades.clear();
        String sql = "SELECT DISTINCT DATE(exam_date) as exam_date " +
                "FROM grades g " +
                "JOIN students s ON g.student_id = s.id " +
                "WHERE s.class_id = ? AND g.subject_id = ? " +
                "AND g.exam_type = ?";

        String examType = (String) examTypeCombo.getSelectedItem();
        if (examType == null || selectedClassId == -1 || selectedSubjectId == -1) return;

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, selectedClassId);
            stmt.setInt(2, selectedSubjectId);
            stmt.setString(3, examType);

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Date date = rs.getDate("exam_date");
                if (date != null) {
                    datesWithGrades.add(removeTime(date));
                    System.out.println("Found grade date: " + date);
                }
            }

            // 强制更新日历显示
            examDateChooser.getJCalendar().getDayChooser().setDecorationBackgroundVisible(true);
            examDateChooser.getJCalendar().getDayChooser().setDecorationBordersVisible(true);
            examDateChooser.getJCalendar().updateUI();

            // 如果当前选中的日期有成绩，设置背景色
            if (examDateChooser.getDate() != null) {
                Date currentDate = removeTime(examDateChooser.getDate());
                boolean hasGrades = datesWithGrades.stream()
                        .anyMatch(d -> removeTime(d).equals(currentDate));

                if (hasGrades) {
                    examDateChooser.setBackground(new Color(255, 100, 100));
                } else {
                    examDateChooser.setBackground(UIManager.getColor("TextField.background"));
                }
            }

            System.out.println("Found " + datesWithGrades.size() + " dates with grades");
            datesWithGrades.forEach(date ->
                    System.out.println("Date with grade: " + new SimpleDateFormat("yyyy-MM-dd").format(date))
            );

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 修改 removeTime 方法，确保日期比较的一致性
    private Date removeTime(Date date) {
        if (date == null) return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
}
